<template>
  <div class="pdf__summrize">
    <div class="transform__upload" v-show="['wait', 'upload'].includes(chatStore.docSummarize.status)">
      <el-upload
        class="upload-demo"
        action="/"
        accept=".pdf"
        :disabled="chatStore.docSummarize.status !== 'wait'"
        drag
        :auto-upload="true"
        :multiple="false"
        :show-file-list="false"
        :file-list="fileList"
        :limit="1"
        :before-upload="handleBeforeUpload"
        :http-request="handleUploadFile"
      >
        <div class="upload__icon">
          <img
            :src="defaultIconUrl"
            width="64"
            height="64"
            alt=""
          />
        </div>
        <template v-if="chatStore.docSummarize.status === 'upload'">
          <div class="upload__progress">
            <p class="mb-12">{{ fileName }}</p>
            <el-progress
              color="#4E5FFF"
              :stroke-width="4"
              :percentage="chatStore.docSummarize.process"
              :show-text="false"
            />
            <p class="mt-8 link-color" v-if="chatStore.docSummarize.process === 100">分析中...</p>
            <p class="mt-8 link-color" v-else>上传中 {{ chatStore.docSummarize.process.toFixed(0) }}%</p>
          </div>
        </template>
        <template v-else>
          <p class="mb-8 fs-14">上传PDF文件格式</p>
          <!-- <p class="fs-c-3 mb-4">点击或拖拽文件到此区域进行AI总结</p> -->
          <p class="fs-c-3 fs-12 mb-4">点击此区域进行AI总结</p>
          <p class="fs-c-3 fs-12 mb-4">(暂不支持扫描件)</p>
        </template>
      </el-upload>
    </div>
    <div class="doc__summarize_user mt-10" v-show="!['', 'wait', 'upload'].includes(chatStore.docSummarize.status)">
      <p class="content__header fs-14">
        <svg-icon icon-class="menu-summarize" class="fs-20 flex-shrink-0"></svg-icon>
        <span>总结 - PDF</span>
      </p>
      <div class="content__body mt-14">
        <svg-icon icon-class="pdf-color-btn" class="fs-16 flex-shrink-0"></svg-icon>
        <span class="split__line"></span>
        <p class="title" :title="chatStore.docSummarize.document.title">
          {{ chatStore.docSummarize.document.title }}
        </p>
      </div>
    </div>
    <div class="doc__summarize_reponse mt-10" v-show="['error', 'end', 'chating'].includes(chatStore.docSummarize.status)">
      <div class="content__body server__content">
        <div class="doc__summarize__error" v-if="isShowError">
          <img src="@/assets/error-robot.png" width="32" height="32" />
          <p class="error-text color-error" v-if="responseCode === 4003">
            当前PDF总结次数已达上限，<span
              class="vip-color cursor"
              @click="$gotoMember()"
              >升级权限</span
            >
          </p>
          <error-message :text="responseErrMsg" v-else-if="responseCode===1009" />
          <error-message v-else />
        </div>
        <div class="doc__summarize__content" v-else>
          <div class="models">
            <img v-if="modelIconUrl" :src="modelIconUrl" width="16" height="16" alt="" srcset="" />
            <svg-icon
              v-else
              :icon-class="formatModelTypeIcon(chatStore.docSummarize.documentModel)"
              class="fs-20"
            ></svg-icon>
            <span>{{ chatStore.docSummarize.documentModelName }}</span>
          </div>
          <div class="models__tile mt-12">
            <svg-icon icon-class="menu-summarize" class="fs-24"></svg-icon>
            <span>文档总结</span>
            <svg-icon
              icon-class="copy-btn"
              class="copy__btn hover-svg fs-18"
              @click="handleCopyBtn()"
            ></svg-icon>
          </div>
          <div class="server__conent_body markedown__body" v-html="message"></div>
        </div>
        <quetions-list
          v-show="chatStore.docSummarize.status === 'end' && questions.length > 0"
          :quetions="questions"
          @click-item="handleQsClick"
        />
      </div>
    </div>
    <div class="actions__status">
      <p v-if="chatStore.docSummarize.status === 'analysis'">
        <svg-icon icon-class="loading" class="fs-16 loading-btn"></svg-icon>
        <span>文档总结分析中</span>
      </p>
      <p v-if="isShowError" @click="handleRegenerate">
        <svg-icon icon-class="refresh-btn" class="fs-16 mr-6"></svg-icon>
        <span>重新生成</span>
      </p>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { formatFilePath, formatModelTypeIcon, copyFunc, rendererMD } from '@/utils'
import createDocFunc from '@/utils/chat-document'
import QuetionsList from '@/components/summarize/quetions.vue'
import ErrorMessage from '@/components/error-message/index.vue'

const { startChatDocument } = createDocFunc()
export default {
  name: 'HomeChat',
  inject: ['sendMessage'], // 接收方法
  components: {
    QuetionsList,
    ErrorMessage
  },
  props: {
  },
  data () {
    return {
      fileList: [],
      fileName: '',
      defaultIconUrl: require('@/assets/upload-pdf-summarize.png')
    }
  },
  computed: {
    ...mapGetters(['chatStore', 'userInfo']),
    message () {
      return rendererMD(this.chatStore.docSummarize.document.summary || '')
    },
    questions () { return this.chatStore.docSummarize.questions },
    modelIconUrl () {
      return this.chatStore.documentModels.find((item) => item.model === this.chatStore.docSummarize.documentModel)?.icon
    },

    isShowError () {
      return this.chatStore.docSummarize.status === 'error' ||
    (this.chatStore.docSummarize.status === 'end' && !this.chatStore.docSummarize.document.summary)
    },

    responseCode () { return this.chatStore.docSummarize.code },

    responseErrMsg () { return this.chatStore.docSummarize.errMsg }
  },
  watch: {
    'chatStore.docSummarize.status' () {
      if (this.chatStore.docSummarize.status === 'wait') {
        this.fileList = []
      }
    }
  },
  methods: {
    formatModelTypeIcon,
    handleCopyBtn () {
      copyFunc(this.chatStore.docSummarize.document.summary || '')
    },
    handleBeforeUpload (file) {
      const { ext } = formatFilePath(file.name)
      if (ext !== 'pdf') {
        this.$PsMessage({ message: `当前只支持PDF文件!` })
        return false
      }
      if (!this.userInfo.is_member && file.size > 1024 * 1024 * 5 && process.env.VUE_APP_BUY_TYPE === 'right') {
        this.$PsMessageBox({
          title: '升级VIP',
          message: `非会员文件大小不能超过5MB!`,
          confirmButtonText: '去升级VIP',
          cancelButtonText: '知道了',
          // iconClass: 'warning',
          width: 312,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.$gotoMember()
            }
            done()
          }
        })
        return false
      }
      if (file.size > 1024 * 1024 * 20) {
        this.$PsMessage({ message: `文件大小不能超过20MB` })
        return false
      }
      return true
    },

    async handleUploadFile  (opt) {
      this.fileName = opt.file.name
      await startChatDocument('pdf', { file: opt.file, title: this.fileName })
      if (this.chatStore.docSummarize.status === 'end') {
        this.fileList = []
      }
    },

    handleRegenerate () {
      const file = this.fileList[0]?.raw || window.__tmp_xz_chat_pdf_file__
      startChatDocument('pdf', {
        file: file,
        title: file.name
      })
    },

    handleQsClick (q) {
      this.sendMessage(q.question)
    }
  }
}

</script>

<style lang="scss" scoped>
.doc__summarize_reponse {
  font-size: 12px;
}
/deep/ .el-upload__input {
  display: none;
}
/deep/.el-upload-dragger {
  padding: 40px 10px;
  background-color: rgba($color-white, 0.1);
  border: 1px dashed rgba($color-primary3, 0.5);
  border-radius: 6px;
  box-sizing: border-box;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-spacing: 4px;
  .fs-c-3 {
    color: rgba(255, 255, 255, 0.5);
  }
}
.transform__upload {
  margin-top: 10px;
  padding-top: 10px;
}
.doc__summarize_user {
  padding: 14px 20px;
  background: rgba(255,255,255,0.1);
  padding: 14px 20px;
  border-radius: $border-radius;
  border-bottom-right-radius: 0;
  font-size: $font-size-base;
  box-shadow: 0px 0px 20px 0px rgba(64,135,243,0.1);
  line-height: 1.8;
}
.content__header {
  --color-primary: #{$color-primary};
  --color-active: #f49f17;
  display: flex;
  align-items: center;
  gap: 4px;
}
.content__body {
  padding: 10px;
  background: rgba(255,255,255,0.1);
  display: flex;
  align-items: center;
  border-radius: 5px;
  box-sizing: border-box;
  cursor: pointer;
  gap: 12px;
  .split__line {
    width: 1px;
    height: 14px;
    background: $border-color-primary;
  }
  .title {
    line-height: 1.4;
    // 超过两行省略
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.server__content {
  display: block;
  width: 100%;
  padding: 20px;
  background: rgba(78,95,255,0.2);
  border-radius: 8px 8px 8px 0px;
  color: $color-white;
  cursor: default;
}
.models {
  display: flex;
  align-items: center;
  gap: 6px;
}

.models__tile {
  --color-primary: #{$color-white};
  --color-active: #{$color-white};
  display: flex;
  align-items: center;
  gap: 6px;
  .copy__btn {
    margin-left: auto;
  }
}
.server__conent_body {
  padding: 10px 0;
  line-height: 1.8;
  font-size: 14px;
}
.actions__status {
  text-align: center;
  p {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: rgba($chat-server-item-gb, 0.7);
    padding: 7px 20px;
    border-radius: 24px;
    color: $color-white;
    font-size: $font-size-base;
    margin: 10px;
    cursor: pointer;
  }
  .loading-btn {
    animation: loading-rotate-infinite 2s linear infinite;
  }
}

@keyframes loading-rotate-infinite {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.upload__progress {
  padding: 0 45px;
  & > p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/deep/.el-progress-bar__outer {
  background-color: rgba($color: $color-primary, $alpha: 0.2);
}
.doc__summarize__error {
  display: flex;
  flex-dicrection: column;
}
</style>
